﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VanTaiBLL;
using VanTaiData;
using VanTaiProperty;
using Roles;
using System.Web.UI.HtmlControls;

namespace VanTaiTMS.Page
{
    public partial class chi_tiet_hang_hoa : System.Web.UI.Page
    {
        #region[Define]
        private DataTable dtDoLine;
        private DataTable dtDo_Line_Detail_Edit;
        private DataTable dtDO;
        private DataTable dtSearch;
        protected string SuggestionList;
        protected string StrAlert = "";
        private DataTable dtAutoComplete;
        private static bool flag = false;
        private TMDoNew_BusinessLogic clsDo = new TMDoNew_BusinessLogic();
        private clsTMDoLineBusiness clsDoLine= new clsTMDoLineBusiness();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            Autocomplate();
            if (!IsPostBack)
            {
                BindGridDO_BILL();
                BindGridDO();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            flag = true;
            lbThongBaoLoi.Text = "";
            drMaPhieuCT.Enabled = true;
            txtMaHangHoa.Enabled = true;

            txtSoLuong.Enabled = true;
            txtDonViTinh.Enabled = true;
            txtTongTien.Enabled = true;
            ClearTextBox();
            OpenDialog("#chitiethanghoa");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            drMaPhieuCT.Enabled = false;
            txtMaHangHoa.Enabled = false;
            txtMaHangHoa.Enabled = false;

            txtSoLuong.Enabled = false;
            txtDonViTinh.Enabled = false;
            txtTongTien.Enabled = false;
            imgSave.Visible = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        BindGridDO_Detail_Edit(Convert.ToInt32(ListViewAll.DataKeys[i].Value.ToString()));
                        OpenDialog("#chitiethanghoa");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            VanTaiBLL.clsTMDoLineBusiness.DeleteTMDoLine(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                        }
                        catch (Exception ex)
                        {
                            lbThongBaoXoa.Text = ex.ToString();
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
            BindGridDO_BILL();
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search(txtSearch.Text);
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            BindGridDO_BILL();
        }
        //-------------------List-View-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyCTHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtMaHangHoa.Enabled = false;
                drMaPhieuCT.Enabled = false;

                txtSoLuong.Enabled = false;
                txtDonViTinh.Enabled = false;
                txtTongTien.Enabled = false;
                imgSave.Visible = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridDO_Detail_Edit(int.Parse(SenderId));
                        OpenDialog("#chitiethanghoa");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridDO_Detail_Edit(int.Parse(SenderId));
                        OpenDialog("#chitiethanghoa");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                LinkButton linkListName = (LinkButton)e.Item.FindControl("linkListName");
                LinkButton linkListName_E = (LinkButton)e.Item.FindControl("linkListName_E");
                string _jsDouble1 = ClientScript.GetPostBackClientHyperlink(linkListName, "");


                linkListName.Attributes["ondblclick"] = _jsDouble1;
                linkListName.Attributes["onclick"] = "return false;";
            }
        }
        //-------------------Data-Pagger---------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            DataPagerListAll.PageSize = 17;
            BindGridDO_BILL();
        }
        //-------------------Button-Popup--------------------
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (drMaPhieuCT.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn mã phiếu chi tiết !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMaHangHoa.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mã hàng hoá !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtDonViTinh.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào đơn vị tính !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtNgayXuat.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền ngày lập phiếu CT !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtSoLuong.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào số lượng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTongTien.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào tổng tiền !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTrongLuong.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào trọng lượng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drMaPhieuCT.SelectedValue.ToString() != "-1" && txtMaHangHoa.Text != ""
                && txtDonViTinh.Text != "" && txtNgayXuat.Text != ""
                && txtSoLuong.Text != "" && txtTongTien.Text != ""
                && txtTrongLuong.Text != "")
            {
                Insert();
            }
        }
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {
            
        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        //----------------Dropdownlist----------------------
        protected void drHangHoa_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }
        #endregion

        #region[Function]
        protected void BindGridDO_BILL()
        {
            dtDoLine = clsDoLine.Search(txtSearch.Text);
            if (dtDoLine != null && dtDoLine.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtDoLine;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
            }
        }
        protected void BindGridDO_Detail_Edit(int id)
        {
            dtDo_Line_Detail_Edit = clsDoLine.BindGirdTMDoLineDetail(id);
            if (dtDo_Line_Detail_Edit != null && dtDo_Line_Detail_Edit.Rows.Count > 0)
            {
                lbID.Text = dtDo_Line_Detail_Edit.Rows[0]["RowID"].ToString();
                lbIDXoa.Text = dtDo_Line_Detail_Edit.Rows[0]["RowID"].ToString();
                drMaPhieuCT.SelectedValue = dtDo_Line_Detail_Edit.Rows[0]["No_"].ToString();
                txtMaHangHoa.Text = dtDo_Line_Detail_Edit.Rows[0]["ItemNo"].ToString();
                txtDonViTinh.Text = dtDo_Line_Detail_Edit.Rows[0]["Unit"].ToString();
                txtTrongLuong.Text = dtDo_Line_Detail_Edit.Rows[0]["NetWeight"].ToString();
                txtSoLuong.Text = dtDo_Line_Detail_Edit.Rows[0]["Amount"].ToString();
                txtTongTien.Text = String.Format("{0:0.00}", dtDo_Line_Detail_Edit.Rows[0]["Total"]).ToString().Replace(".", ",");
                txtGhiChu.Text = dtDo_Line_Detail_Edit.Rows[0]["Description"].ToString();
                txtNgayXuat.Text = String.Format("{0:dd/MM/yyyy}", dtDo_Line_Detail_Edit.Rows[0]["PostingDate"]).ToString();
            }
        }
        protected void BindGridDO()
        {
            dtDO = clsDo.GetData();
            if (dtDO != null && dtDO.Rows.Count > 0)
            {
                drMaPhieuCT.DataSource = dtDO;
                drMaPhieuCT.DataTextField = "No_";
                drMaPhieuCT.DataValueField = "No_";
                drMaPhieuCT.DataBind();
            }
        }
        protected void Insert()
        {
            //Insert
            if (flag)
            {
                InsertDO();
            }
            else//Update
            {
                UpdateDO();
            }
        }
        protected void InsertDO()
        {
            try
            {
                VanTaiProperty.clsTMDoLineProperty obj = new clsTMDoLineProperty();
                obj.No_ = drMaPhieuCT.SelectedValue.ToString();
                obj.ItemNo = txtMaHangHoa.Text;
                obj.Unit = txtDonViTinh.Text;
                obj.NetWeight = float.Parse(txtTrongLuong.Text.Replace(",", "."));
                obj.Amount = int.Parse(txtSoLuong.Text);
                obj.Total = float.Parse(txtTongTien.Text.Replace(",", "."));
                obj.PalletNo = DBNull.Value.ToString();
                obj.TypeCell = 0;
                obj.CellNewStatus = 0;
                obj.CellNo = DBNull.Value.ToString();
                obj.Description = txtGhiChu.Text;
                obj.DocumentDate = DateTime.Today;
                obj.PostingDate = DateTime.Parse(txtNgayXuat.Text);
                obj.ExpiryDate = DateTime.Today;
                obj.UserID = DBNull.Value.ToString();
                obj.Status = 0;
                VanTaiBLL.clsTMDoLineBusiness.InsertTMDoLine(obj);
                lbThongBaoLoi.Text = "Thêm mẫu tin thành công !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridDO_BILL();
                ClearTextBox();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void UpdateDO()
        {
            try
            {
                VanTaiProperty.clsTMDoLineProperty obj = new clsTMDoLineProperty();
                obj.RowID = int.Parse(lbID.Text);
                obj.No_ = drMaPhieuCT.SelectedValue.ToString();
                obj.ItemNo = txtMaHangHoa.Text;
                obj.Unit = txtDonViTinh.Text;
                obj.NetWeight = float.Parse(txtTrongLuong.Text.Replace(",", "."));
                obj.Amount = int.Parse(txtSoLuong.Text);
                obj.Total = float.Parse(txtTongTien.Text.Replace(",", "."));
                obj.PalletNo = DBNull.Value.ToString();
                obj.TypeCell = 0;
                obj.CellNewStatus = 0;
                obj.CellNo = DBNull.Value.ToString();
                obj.Description = txtGhiChu.Text;
                obj.DocumentDate = DateTime.Today;
                obj.PostingDate = DateTime.Parse(txtNgayXuat.Text);
                obj.ExpiryDate = DateTime.Today;
                obj.UserID = DBNull.Value.ToString();
                obj.Status = 0;
                VanTaiBLL.clsTMDoLineBusiness.UpdateTMDoLine(obj);
                lbThongBaoLoi.Text = "Cập nhật mẫu tin thành công !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridDO_BILL();
                ClearTextBox();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        //AutoComplate
        protected void Autocomplate()
        {
            dtAutoComplete = clsDoLine.BindGirdTMDoLine(string.Empty);
            if (dtAutoComplete != null && dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["No_"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["ItemNo"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["No_"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["ItemNo"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }
        protected void Search(string keywords)
        {
            dtSearch = clsDoLine.Search(keywords);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + dtSearch.Rows.Count.ToString() + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }
        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        private void CloseDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        #endregion

        #region[Clear-TextBox]
        protected void ClearTextBox()
        {
            drMaPhieuCT.SelectedIndex = -1;
            txtMaHangHoa.Text = string.Empty;
            txtDonViTinh.Text = string.Empty;
            txtGhiChu.Text = string.Empty;
            txtNgayXuat.Text = string.Empty;
            txtSearch.Text = string.Empty;
            txtSoLuong.Text = "0";
            txtTongTien.Text = "0";
            txtTrongLuong.Text = "0";
        }
        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLyCTHangHoa, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLyCTHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyCTHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLyCTHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}